<template>
  <div class="container">
    <xy-table
      :addFormDTO="addForm"
      :api="api"
      :columns="columns"
      :on-check="onAudit"
      :on-delete="onDelete"
      :on-edit="editItem"
      @selection-change="handleSelectionChange"
      ref="table"
    >
      <template #addItem>
        <div class="row">
          <!-- <add-dialog
            :apiName="api.create"
            :model="addForm"
            class="mr-1"
          ></add-dialog>-->
          <div class="mr-1">
            <el-button
              @click="showAddDialog"
              icon="el-icon-plus"
            >{{ $language.local("Add") }}</el-button>
          </div>

          <div>
            <el-button
              @click="onBatchAudit"
              class="mr-1"
              size="mini"
            >
              <i class="el-icon-s-check"></i>
              {{ $language.local("批量认证") }}
            </el-button>
          </div>
          <div>
            <el-button
              @click="uploadFile"
              class="mr-1"
              size="mini"
            >
              <i class="el-icon-upload2"></i>
              {{ $language.local("批量导入") }}
            </el-button>
          </div>

          <div>
            <el-button
              @click="openMiniProgram"
              class="ml0"
              size="mini"
            >
              <i class="el-icon-full-screen"></i>
              {{ $language.local("签约小程序") }}
            </el-button>
          </div>
        </div>
        <search-header
          :model="args"
          :on-search="onSearch"
          class="ml-1"
        >
          <template #operation></template>
        </search-header>
      </template>
      <template #selection>
        <el-table-column
          :selectable="isDisabled"
          align="center"
          type="selection"
        ></el-table-column>
      </template>
      <template #check="{ row }">
        <el-button
          @click="onAudit(row)"
          type="text"
        >认证</el-button>
      </template>
    </xy-table>

    <!-- #region Add Employee -->
    <el-dialog
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :title="$language.local('添加')"
      :visible.sync="addDialogVisible"
      width="62%"
    >
      <el-form
        :model="addForm"
        :rules="$rules"
        class="grid-flex"
        label-width="100px"
        ref="addFromRef"
      >
        <!-- @validate="onValidate" -->
        <!-- #region ServiceId -->
        <el-form-item
          :label="$language.local('ServiceID')"
          prop="ServiceID"
        >
          <select-service v-model="addForm['ServiceID']"></select-service>
        </el-form-item>
        <!-- #endregion -->
        <!-- #region MID -->
        <el-form-item
          :label="$language.local('MID')"
          prop="MID"
        >
          <select-merchantid v-model="addForm['MID']"></select-merchantid>
        </el-form-item>
        <!-- #endregion -->
        <!-- #region ServiceContentId -->
        <el-form-item
          :label="$language.local('ServiceContentId')"
          prop="ServiceContentId"
        >
          <select-id
            apiName="/api/Common/GetdictionaryItem?typenum=002"
            label-key="name"
            v-model="addForm['ServiceContentId']"
          ></select-id>
        </el-form-item>
        <!-- #endregion -->
        <!-- #region EmpName -->
        <el-form-item
          :label="$language.local('EmpName')"
          prop="EmpName"
        >
          <xy-input
            clearable
            v-model="addForm['EmpName']"
          ></xy-input>
        </el-form-item>
        <!-- #endregion -->
        <!-- #region IdCardNo -->
        <el-form-item
          :label="$language.local('IdCardNo')"
          prop="IdCardNo"
        >
          <xy-input
            clearable
            v-model="addForm['IdCardNo']"
          ></xy-input>
        </el-form-item>
        <!-- #endregion -->

        <!-- #region BankNanme -->
        <el-form-item
          :label="$language.local('BankName')"
          prop="BankName"
        >
          <select-bank v-model="addForm.BankName"></select-bank>
        </el-form-item>
        <!-- #endregion -->
        <!-- #region BankCardNo -->
        <el-form-item
          :label="$language.local('BankCardNo')"
          prop="BankCardNo"
        >
          <xy-number v-model="addForm['BankCardNo']"></xy-number>
        </el-form-item>
        <!-- #endregion -->

        <!-- #region EmpPhone -->
        <el-form-item
          :label="$language.local('EmpPhone')"
          prop="EmpPhone"
        >
          <xy-input
            clearable
            v-model="addForm['EmpPhone']"
          ></xy-input>
        </el-form-item>
        <!-- #endregion -->
      </el-form>
      <div
        class="dialog-footer"
        slot="footer"
      >
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          @click="onAddSubmit('addFromRef')"
          type="primary"
        >确 定</el-button>
      </div>
    </el-dialog>
    <!-- #endregion -->

    <el-dialog
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :visible.sync="editDialogVisible"
      title="修改"
      width="30%"
    >
      <el-form
        :model="editFrom"
        :rules="$rules"
        label-width="80px"
        ref="editFromRef"
        status-icon
      >
        <el-form-item
          :label="$language.local('BankName')"
          prop="BankName"
        >
          <select-bank v-model="editFrom.BankName"></select-bank>
        </el-form-item>
        <el-form-item
          :label="$language.local('BankCardNo')"
          prop="BankCardNo"
        >
          <xy-number
            clearable
            v-model="editFrom.BankCardNo"
          ></xy-number>
        </el-form-item>
        <el-form-item
          :label="$language.local('EmpPhone')"
          prop="EmpPhone"
        >
          <xy-input
            clearable
            v-model="editFrom.EmpPhone"
          ></xy-input>
        </el-form-item>
      </el-form>
      <span
        class="dialog-footer"
        slot="footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          @click="onEditSubmit('editFromRef')"
          type="primary"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- #region 批量导入 -->
    <el-dialog
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :visible.sync="uploadDialogVisible"
      class="drag-upload"
      title="批量导入"
      width="62%"
    >
      <el-form
        :model="uploadForm"
        :rules="$rules"
        ref="formRef"
        status-icon
      >
        <el-form-item
          :label="$language.local('serviceName')"
          prop="sid"
        >
          <select-id
            apiName="/api/Common/GetServiceProviderList"
            labelKey="ServiceName"
            v-model="uploadForm.sid"
          ></select-id>
        </el-form-item>
        <el-form-item
          :label="$language.local('excelUrl')"
          prop="excelUrl"
        >
          <upload-file
            :drag="true"
            :on-success="onSuccess"
            v-model="uploadForm.excelUrl"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text mb-3">
              将文件拖到此处，或
              <em>点击选择</em>
            </div>
            <template slot="tip">
              <span hidden></span>
            </template>
          </upload-file>
          <div class>
            上传文件不超过 5 MB,
            <el-button
              @click="downloadFile"
              icon="el-icon-download"
              type="text"
            >灵工模板.xls</el-button>下载
          </div>
        </el-form-item>
      </el-form>
      <div class="update-table"></div>
      <xy-table
        :columns="uploadColumnkeys"
        :list="employeesUpload"
        v-if="employeesUpload.length >0"
      >
        <template #header>
          <span></span>
        </template>
        <template #operation>
          <span></span>
        </template>
        <template #pagination>
          <span></span>
        </template>
      </xy-table>

      <span
        class="dialog-footer"
        slot="footer"
      >
        <el-button
          :disabled="!isUpdateCheckOk"
          @click="uploadFiles"
          type="primary"
        >上传</el-button>
      </span>
    </el-dialog>
    <!-- #endregion -->
    <!-- #region 认证小程序 -->
    <el-dialog
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :visible.sync="miniDialogVisible"
      title="认证小程序"
      width="30%"
    >
      <img
        alt
        src="../../assets/static/img/miniProgram.jpg"
        srcset
        style="width: 100%"
      />
      <span
        class="dialog-footer"
        slot="footer"
      >
        <el-button @click="miniDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- #endregion -->
  </div>
</template>

<script>
import API from "../../plugins/api";
export default {
  inject: ["reload"],
  data() {
    return {
      api: new API("/api/employee"),
      queryColumn: "empName",
      addForm: {
        MID: "",
        EmpName: "",
        IdCardNo: "",
        Sex: "",
        BankName: "",
        BankCardNo: "",
        EmpPhone: "",
        // ServiceContentId: "",
      },
      selectEmp: "",
      editFrom: {
        BankCardNo: "",
        EmpPhone: "",
      },
      columns: {
        EmpName: "梁由之",
        IdCardNo: "510724198510242428",
        BankCardNo: "6228460480014077810",
        // BankCardNos: "6228460480014077810",
        // EmpPhones: "13678289922",
        EmpPhone: "13678289922",
        MerchantName: "长沙新越集团",

        zt: 1,
      },
      uploadColumnkeys: {
        EmpName: "钟平上",
        IdCardNo: "431027199106272031",
        BankCardNo: "6225887115784856",
        EmpPhone: "15116228315",
        types: "更新",
        Error: "",
      },
      isUpdateCheckOk: false,
      employeesUpload: [],
      editDialogVisible: false,
      uploadDialogVisible: false,
      miniDialogVisible: false,
      miniProgramUrl: "../../assets/static/img/miniProgram.jpg",
      uploadForm: {
        sid: "",
        excelUrl: ""
      },
      args: {
        auditStatus: "",
      },
      addDialogVisible: false
    };
  },
  created() {
    this.api.data.edit = "EditById";
    this.api.data.check = "Audit";
  },
  computed: {

  },
  methods: {
    onSearch(e) {
      // this.params = e;
      console.log(e);
      console.log(this.$refs.table);
      this.$refs.table.getData(e);
    },
    async showAddDialog() {
      this.addDialogVisible = true;
    },
    uploadFile() {
      this.uploadDialogVisible = true;
    },
    openMiniProgram() {
      const sUserAgent = navigator.userAgent;
      if (
        sUserAgent.indexOf("Android") > -1 ||
        sUserAgent.indexOf("iPhone") > -1 ||
        sUserAgent.indexOf("iPad") > -1 ||
        sUserAgent.indexOf("iPod") > -1 ||
        sUserAgent.indexOf("Symbian") > -1
      ) {
        window.open("weixin://dl/business/?t=VlUyQ3lib6h");
      } else {
        this.miniDialogVisible = true;
      }
    },
    async uploadFiles() {
      await this.$refs.formRef.validate();
      let response = await this.$http.post(
        "/api/employee/batchInput",
        null,
        this.uploadForm
      );
      console.log(response);

      this.uploadDialogVisible = false;
      this.reload();
    },
    editItem(row) {
      this.editFrom = row;
      this.editDialogVisible = true;
    },
    onAddSubmit(formName) {
      this.$refs[formName].validate(async (valided) => {
        if (!valided) {
          return;
        }

        // this.addForm.employee.empName = this.addForm.empName;
        console.log(this.addForm);
        let query = {
          MID: this.addForm.MID,
          ServiceContentId: this.addForm.ServiceContentId,
        };
        let response = await this.$http.post(
          `${this.apiName}`,
          this.addForm,
          query
        );
        console.log(response);
        if (response.data.Code == 200) {
          console.log(response);
          // this.$message.success("添加成功");
          this.addDialogVisible = false;
          this.reload();
        }

      });
    },
    onEditSubmit(formName) {
      this.$refs[formName].validate(async (valided) => {
        if (!valided) {
          return;
        }
        console.log(this.editFrom);
        let response = await this.$http.post(
          `/api/employee/Edit/${this.editFrom.Id}?mid=${this.editFrom.MID}`,
          this.editFrom
        );
        this.editDialogVisible = false;
        console.log(response);
        this.reload();
      });
    },
    async  onSuccess(e){
      console.log(e);
      let response = await this.$http.post(`/api/employee/CheckExportInData?ExcelUrl=${e.docurl}`);
      console.log(response);
      this.employeesUpload = response.data.Data;
      this.isUpdateCheckOk = this.employeesUpload.every(v=>v.Error === "");

    },
    async downloadFile() {
      // const response = await this.$http.get(
      //   "/api/DataTemplate/GetList?TemplateCode=1"
      // );
      // let url = process.env.VUE_APP_BASEURL + response.data.Data[0].URL;
      let url =
        "http://demo.xinyueai.com/admin/static/template/Settlementtemplate.xlsx";
      this.$common.downloadFile({ url, fileName: "灵工模板" });
    },
    async onDelete(row) {
      await this.$http.delete(`/api/employee/Delete/${row.Id}?mid=${row.MID}`);
      this.reload();
    },
    async  onAudit(e){
      console.log(e);
      await this.$http.post(`/api/employee/Audit/${e.Id}?mid=${e.MID}`);
      this.reload();
    },
    isDisabled(row){
      return row.zt !== 1;
    },
    handleSelectionChange(val = []) {
      this.selectEmp = val;
      console.log(val);
      // this.invoiceTotalAmount = val.reduce(
      //   (total, cur) => total + cur.Amount,
      //   0
      // );
      // console.log(this.invoiceTotalAmount);
      // this.ids = Array.from(val, (v) => v.Id);
      // console.log(this.ids);
    //  let ids = Array.from(val, v=>v.Id);
      //    console.log(ids);
    },
    async  onBatchAudit(){
    //  let list = this.$refs["table"].$refs["multipleTable"];
    //  list.toggleAllSelection();

      await this.$confirm(
        `本次共认证 ${this.selectEmp.length} 名灵工, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((e) => {
        this.$message.info("已取消实名认证！");
        throw e;
      });

      if (this.selectEmp.length === 0) {
        this.$message.error("请先选择灵工，再进行认证！");
        return;
      }
      console.log(this.selectEmp);

    }
  },
};
</script>

<style lang="less" scoped>
.update-table {
  position: relative;
  //padding-bottom: 1rem;
  //min-height: 12rem;
}
// .upload-footer {
//   position: absolute;
//   bottom: 2rem;
//   right: 1rem;
//   z-index: 100;
// }
</style>
